<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人资料</h2>
        </div>
      </template>
      
      <el-form :model="profileForm" :rules="rules" ref="profileFormRef" label-position="top">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="profileForm.currentPassword" type="password" placeholder="请输入当前密码"></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="profileForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="profileForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading" class="update-button">更新资料</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, FormInstance } from 'element-plus'
import api from '../api'

const router = useRouter()
const profileFormRef = ref<FormInstance>()
const loading = ref(false)

const profileForm = reactive({
  username: '',
  email: '',
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== profileForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ]
}

const fetchUserProfile = async () => {
  try {
    // 获取用户资料
    const response = await api.get('/user/profile/')
    const { username, email } = response.data
    profileForm.username = username
    profileForm.email = email
  } catch (error: any) {
    ElMessage.error('获取用户信息失败')
  }
}

const submitForm = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 更新用户资料
        const response = await api.put('/user/profile/', {
          username: profileForm.username,
          email: profileForm.email,
          currentPassword: profileForm.currentPassword,
          newPassword: profileForm.newPassword || undefined
        })
        
        ElMessage.success('个人资料更新成功！')
        // 清空密码字段
        profileForm.currentPassword = ''
        profileForm.newPassword = ''
        profileForm.confirmPassword = ''
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '更新失败，请稍后再试')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  fetchUserProfile()
})
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 64px); /* 减去顶部导航栏的高度 */
  padding: 20px;
  background-color: #f5f7fa;
}

.profile-card {
  width: 500px;
  max-width: 100%;
}

.card-header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.update-button {
  width: 100%;
}
</style>